package com.example.hao.flowercityfm.Fragment;


import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.hao.flowercityfm.Files.Cache;
import com.example.hao.flowercityfm.R;
import com.example.hao.flowercityfm.application.MyApp;
import com.example.hao.flowercityfm.pojo.LiveFragmentData;
import com.example.hao.flowercityfm.utils.HttpUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**直播
 * A simple {@link Fragment} subclass.
 */
public class LiveFragment extends Fragment {
    public static final String TAG = "LiveFragment";
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.fl_live_rv)
    RecyclerView flLiveRv;
    Unbinder unbinder;
    private LiveAdapter liveAdapter;
    private SharedPreferences preferences;
    private SharedPreferences.Editor edit;
    private Cache cache;

    public LiveFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        preferences = context.getSharedPreferences(Cache.FM_DATA, Context.MODE_PRIVATE);
        cache = new Cache(context);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_live, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        readFileJson();
        return view;
    }


    private void initView() {

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {
                readFileJson();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });

        flLiveRv.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        liveAdapter = new LiveAdapter(getActivity());
        flLiveRv.setAdapter(liveAdapter);
        flLiveRv.addItemDecoration(new ItemDecoration(getResources().getDimensionPixelOffset(R.dimen._5dp)));
    }

    /**
     * 规划recycleView(使用GridLayoutManger时) 中 视图之间的间隙的距离
     */
    class ItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public ItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.right = space;
            outRect.left = space;
            outRect.bottom = space;
            outRect.top = space;

        }
    }

    private static final String URL = "https://api.myjson.com/bins/9yc6g";

    private static final String KEY = "LF";
    private static final String VALUE = "999";
    private static final String DEF_VALUE = "null";
    private static final String FILE_NAME = "LFJson.txt";

    /**
     * 网络请求json数据
     */
    private void initData() {
        HttpUtils.method2(URL, new HttpUtils.OnOkCallBack() {
            @Override
            public void onFailure(@NonNull IOException e) {
                Log.e(MyApp.TAG, "onFailure: LiveFragment  " + e.getMessage());
            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onResponse(@NonNull String jsonStr) {
                //网络请求成功,记录一个标记
                edit = preferences.edit();
                edit.putString(KEY, VALUE);
                boolean commit = edit.commit();
                //绑定数据
                bindData(jsonStr);
                //缓存数据

                if (!isNotCache()) {
                    cache.writeFile(FILE_NAME, jsonStr);
                }
            }
        });

    }

    /**
     * @param jsonStr 适配器所需绑定的数据
     */
    private void bindData(String jsonStr) {
        LiveFragmentData liveFragmentData = new Gson().fromJson(jsonStr, LiveFragmentData.class);
        liveAdapter.setLiveData(liveFragmentData);
    }

    /**
     * @return true 没有缓存json数据
     */
    private boolean isNotCache() {
        return preferences.getString(KEY, DEF_VALUE).equals(DEF_VALUE);
    }

    /**
     * 读取缓存
     */
    private void readFileJson(){
        if (isNotCache()) {
            initData();
        } else {
            String file = cache.readFile(FILE_NAME);
            if (file == null) {
                initData();
            } else {
                bindData(file);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * LiveAdapter 适配器
     */
    class LiveAdapter extends RecyclerView.Adapter {

        private Context context;

        private LiveAdapter(Context context) {
            this.context = context;
        }

        private LiveFragmentData liveData;

        void setLiveData(LiveFragmentData liveData) {
            this.liveData = liveData;
//            Log.d(MyApp.TAG, "setLiveData: "+liveData);
            notifyDataSetChanged();
        }


        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {


            return new LiveViewHolder(getLayoutInflater().inflate(R.layout.fragment_live_item, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            LiveFragmentData.DataBean dataBean = liveData.getData().get(position);
            LiveViewHolder viewHolder = (LiveViewHolder) holder;
            Glide.with(context).load(dataBean.getPictureUrl()).into(viewHolder.ivPic);
            Glide.with(context).load(dataBean.getProgramPictureUrl()).into(viewHolder.ivBg);
            viewHolder.tvInformation.setText(dataBean.getInformation());
            viewHolder.tvName.setText(dataBean.getName());
            viewHolder.tvClickSum.setText(String.valueOf(dataBean.getClickSum()));
        }

        @Override
        public int getItemCount() {
            return liveData == null ? 0 : liveData.getData().size();
        }

        class LiveViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_bg)
            ImageView ivBg;
            @BindView(R.id.tv_clickSum)
            TextView tvClickSum;
            @BindView(R.id.iv_pic)
            ImageView ivPic;
            @BindView(R.id.cv)
            CardView cv;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.tv_information)
            TextView tvInformation;

            private LiveViewHolder(View itemView) {
                super(itemView);

                ButterKnife.bind(this, itemView);
            }
        }
    }
}
